package com.huawei.codelab.utils;

import com.huawei.codelab.FmmallDataAbility;
import com.huawei.codelab.slice.LoginAbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

public class DataBaseUtil {
    private  static Uri uri = Uri.parse("dataability:///com.huawei.codelab.FmmallDataAbility/fmmall_info");

    //退出登录方法(删除token即可！！！！)2022.6.9晚报错版 6.10晚修正版(本地数据库以键值对形式存储，key：？，value:?)
    //包含token的一列数据为: key:token value:登录成功  根据key或value删除其一即可删整列
    public static int removetoken(String key,Context context){
        //helper:操作帮助器  原文：https://ost.51cto.com/posts/3217
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);
        // 构造删除条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        String msg = LoginAbilitySlice.msg;
        predicates.equalTo("key", key);
//        借助helper操作uri表
        try {
            dataAbilityHelper.delete(uri,predicates);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        return 0;
    }
//    public static int removetoken1(Context context){
//        FmmallDataAbility fmmallDataAbility = new FmmallDataAbility();
//        // 构造删除条件
//        DataAbilityPredicates predicates = new DataAbilityPredicates();
//        predicates.equalTo("token","token");
////        借助helper操作uri表
//        int i = fmmallDataAbility.delete(uri, predicates);
//        return i;
//    }

    public static String getvalue(String key, Context context){
        String value =null;
        //访问本地数据库，查看是否存在本地数据库
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);

//        String[] columns ={"id","key","value"};
        String[] columns ={"value"};
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo("key",key);
        try {
            ResultSet rs = dataAbilityHelper.query(uri, columns, predicates);
            if(rs.getRowCount()>0){
                rs.goToFirstRow();
                 value =rs.getString(0);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static int setValue(String key,String value,Context context){
        int i=0;
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString("key",key);
        valuesBucket.putString("value",value);

        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);

        try {
            i = dataAbilityHelper.insert(uri, valuesBucket);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
               return i;

    }



}
